<template>
  <div>
    <DynamicTable
      ref="dynamicTableRef"
      row-key="id"
      :header-title="$t('routes.system.system.service.list')"
      :data-request="loadData"
      :columns="columns"
      bordered
      size="small"
      :showIndex="false"
      :fetch-config="{ listField: 'data', totalField: 'count' }"
    >
      <template #toolbar>
        <a-button v-if="canAdd" type="primary" @click="edit">
          {{ $t('common.add') }}
        </a-button>
      </template>
    </DynamicTable>
  </div>
</template>
<script lang="tsx" setup>
  import { ref } from 'vue'
  import { message } from 'ant-design-vue'
  import { DynamicTable } from '@/components/core/dynamic-table'
  import { useFormModal } from '@/hooks/useModal/useFormModal'
  import type { FormSchema } from '@/components/core/schema-form/src/types/form'
  import type { TableColumn } from '@/components/core/dynamic-table'
  import { useI18n } from '@/hooks/useI18n'
  import { ApiDescription, HttpMethod } from '@/utils/apiDescription'
  import canAccessView from '@/utils/accessCheck'
  import { getAllService, addService, updateService, deleteService } from '@/api/middleSystem'

  defineOptions({
    name: 'Service',
  })

  const canAdd = ref(canAccessView(new ApiDescription('/service', HttpMethod.Post)))
  const canUpdate = ref(canAccessView(new ApiDescription('/service/{appId}', HttpMethod.Put)))
  const canDelete = ref(canAccessView(new ApiDescription('/service/{appId}', HttpMethod.Delete)))

  const { t } = useI18n()
  const dynamicTableRef = ref<InstanceType<typeof DynamicTable>>()

  /**
   * 表格列
   */
  const columns: TableColumn<any>[] = [
    {
      title: '服务唯一标识',
      dataIndex: 'appId',
      hideInSearch: true,
    },
    {
      title: '服务名称',
      dataIndex: 'name',
    },
    {
      title: '服务英文名称',
      dataIndex: 'englishName',
      hideInSearch: true,
    },
    {
      title: '服务ip',
      dataIndex: 'endpoints.ip',
      hideInSearch: true,
      width: 200,
      customRender: ({ record }) => {
        return record.endpoints.ip
      },
    },
    {
      title: '服务端口',
      dataIndex: 'endpoints.port',
      hideInSearch: true,
      customRender: ({ record }) => {
        return record.endpoints.port
      },
    },
    {
      title: '服务秘钥',
      dataIndex: 'endpoints.appSecret',
      hideInSearch: true,
      customRender: ({ record }) => {
        return record.endpoints.appSecret
      },
    },
    {
      title: '版本号',
      dataIndex: 'defaultVersion',
      hideInSearch: true,
    },
    {
      title: '是否支持用户管理',
      dataIndex: 'userInfoManage',
      hideInSearch: true,
      customRender: ({ record }) => {
        if (record.userInfoManage) {
          return <span style="color:#67C23A">是</span>
        } else {
          return <span style="color:#F56C6C">否</span>
        }
      },
    },
    {
      title: '服务角色标识',
      dataIndex: 'userRoleTags',
      hideInSearch: true,
      customRender: ({ record }) => {
        let dom = ''
        if (record.userRoleTags?.length) {
          Object.keys(record.userRoleTags).map(el => {
            dom += <div>{el}</div>
          })
        }
        return dom
      },
    },
    {
      title: '是否节点在线',
      dataIndex: 'state',
      hideInSearch: true,
      customRender: ({ record }) => {
        if (record.state) {
          return <span style="color:#67C23A">是</span>
        } else {
          return <span style="color:#F56C6C">否</span>
        }
      },
    },
    {
      title: '是否启用',
      dataIndex: 'enabled',
      hideInSearch: true,
      customRender: ({ record }) => {
        if (record.enabled) {
          return <span style="color:#67C23A">是</span>
        } else {
          return <span style="color:#F56C6C">否</span>
        }
      },
    },
    {
      title: '日志追踪',
      dataIndex: 'trace',
      hideInSearch: true,
      customRender: ({ record }) => {
        if (record.trace) {
          return <span style="color:#67C23A">是</span>
        } else {
          return <span style="color:#F56C6C">否</span>
        }
      },
    },
    {
      title: '操作',
      dataIndex: 'ACTION',
      hideInSearch: true,
      width: 200,
      actions: ({ record }) => [
        {
          label: t('common.edit'),
          hide: !canUpdate.value,
          onClick: () => edit(record),
        },
        {
          label: t('common.delete'),
          danger: true,
          hide: !canDelete.value,
          popConfirm: {
            title: t('column.confirmDel'),
            onConfirm: () => del(record),
          },
        },
      ],
    },
  ]

  /**
   * 加载数据
   */
  const loadData = async params => {
    const { name, pageIndex, pageSize } = params
    const data = await getAllService(pageIndex, pageSize, name)
    return data
  }

  const [showModal] = useFormModal()
  const formSchemas: FormSchema[] = [
    {
      field: 'appId',
      component: 'Input',
      label: '唯一标识',
      rules: [{ required: true }],
    },
    {
      field: 'name',
      component: 'Input',
      label: '服务名称',
      rules: [{ required: true }],
    },
    {
      field: 'englishName',
      component: 'Input',
      label: '英文名称',
      rules: [{ required: true }],
    },
    {
      field: 'endpoints.ip',
      component: 'Input',
      label: '服务ip',
      rules: [{ required: true }],
      defaultValue: '',
    },
    {
      field: 'endpoints.port',
      component: 'Input',
      label: '服务端口',
      rules: [{ required: true }],
      defaultValue: '',
    },
    {
      field: 'endpoints.appSecret',
      component: 'Input',
      label: '服务密钥',
      rules: [{ required: true }],
      defaultValue: '',
    },
    {
      field: 'endpoints.protocol',
      component: 'Input',
      label: '网络协议',
      rules: [{ required: true }],
      defaultValue: '',
    },
    {
      field: 'defaultVersion',
      component: 'Input',
      label: '默认版本',
      rules: [{ required: true }],
    },
    {
      field: 'state',
      component: 'Switch',
      label: '节点在线',
      defaultValue: false,
    },
    {
      field: 'enabled',
      component: 'Switch',
      label: '是否启用',
      defaultValue: false,
    },
    {
      field: 'trace',
      component: 'Switch',
      label: '日志追踪',
      defaultValue: false,
    },
  ]

  /**
   * 打开新增/编辑弹窗
   */
  const edit = async record => {
    const [formRef] = await showModal({
      modalProps: {
        title: `${record.appId ? t('common.edit') : t('common.add')}`,
        width: '40%',
        onFinish: async values => {
          const { appId, name, englishName, endpoints, defaultVersion, state, enabled, trace } =
            values
          if (record.appId)
            await updateService(
              record.appId,
              name,
              englishName,
              endpoints,
              defaultVersion,
              state,
              enabled,
              trace,
            )
          else
            await addService(
              appId,
              name,
              englishName,
              endpoints,
              defaultVersion,
              state,
              enabled,
              trace,
            )
          message.success('操作成功')
          dynamicTableRef.value?.reload()
        },
      },
      formProps: {
        labelWidth: 100,
        layout: 'horizontal',
        schemas: record.appId
          ? formSchemas.filter(
              item => item.field !== 'endpoints.protocol' && item.field !== 'appId',
            )
          : formSchemas,
      },
    })

    if (record.appId) {
      formRef?.setFieldsValue({
        name: record.name,
        englishName: record.englishName,
        'endpoints.ip': record.endpoints.ip,
        'endpoints.port': record.endpoints.port,
        'endpoints.appSecret': record.endpoints.appSecret,
        defaultVersion: record.defaultVersion,
        state: record.state,
        enabled: record.enabled,
        trace: record.trace,
      })
    }
  }

  /**
   * 删除
   */
  const del = async record => {
    await deleteService(record.appId)
    message.success('操作成功')
    dynamicTableRef.value?.reload()
  }
</script>
